package top.jnaw.jee.utils;

import static top.jnaw.jee.platform.Consts.REGEX_MOBILE;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import java.security.MessageDigest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import top.jnaw.jee.platform.Consts;
import top.jnaw.jee.platform.Consts.Result;


/**
 * Created by lc on 17-6-1.
 */
public class Strings {

  private static final char HEX[] = {'0', '1', '2', '3', '4', '5', '6', '7',
      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

  private static final Map<String, String> LOCAL_CODE = new HashMap<>();
  private static final String[] ID_SUFFIX = {"1", "0", "x", "9", "8", "7", "6",
      "5", "4", "3", "2"};
  private static final String[] ID_WI = {"7", "9", "10", "5", "8", "4", "2",
      "1", "6", "3", "7", "9", "10", "5", "8", "4", "2"};

  static {
    LOCAL_CODE.put("11", "北京");
    LOCAL_CODE.put("12", "天津");
    LOCAL_CODE.put("13", "河北");
    LOCAL_CODE.put("14", "山西");
    LOCAL_CODE.put("15", "内蒙古");
    LOCAL_CODE.put("21", "辽宁");
    LOCAL_CODE.put("22", "吉林");
    LOCAL_CODE.put("23", "黑龙江");
    LOCAL_CODE.put("31", "上海");
    LOCAL_CODE.put("32", "江苏");
    LOCAL_CODE.put("33", "浙江");
    LOCAL_CODE.put("34", "安徽");
    LOCAL_CODE.put("35", "福建");
    LOCAL_CODE.put("36", "江西");
    LOCAL_CODE.put("37", "山东");
    LOCAL_CODE.put("41", "河南");
    LOCAL_CODE.put("42", "湖北");
    LOCAL_CODE.put("43", "湖南");
    LOCAL_CODE.put("44", "广东");
    LOCAL_CODE.put("45", "广西");
    LOCAL_CODE.put("46", "海南");
    LOCAL_CODE.put("50", "重庆");
    LOCAL_CODE.put("51", "四川");
    LOCAL_CODE.put("52", "贵州");
    LOCAL_CODE.put("53", "云南");
    LOCAL_CODE.put("54", "西藏");
    LOCAL_CODE.put("61", "陕西");
    LOCAL_CODE.put("62", "甘肃");
    LOCAL_CODE.put("63", "青海");
    LOCAL_CODE.put("64", "宁夏");
    LOCAL_CODE.put("65", "新疆");
    LOCAL_CODE.put("71", "台湾");
    LOCAL_CODE.put("81", "香港");
    LOCAL_CODE.put("82", "澳门");
    LOCAL_CODE.put("91", "国外");
  }

  public static String suffix(String file) {
    String result = "";

    if (null != file) {
      String[] array = file.split("\\.");
      int length = array.length;

      if (length > 1) {
        result = "." + array[length - 1];
      }
    }

    return result;
  }
  /**
   * 加工输出 JSON 数组
   */
  public static String dump(JSONArray json) {
    StringBuilder sBuilder = new StringBuilder();

    if (null == json || 0 == json.size()) {
      return sBuilder.toString();
    }

    int size = json.size();
    for (int i = 0; i < size; ++i) {
      sBuilder.append(json.get(i).toString()).append(", \n");
    }

    int length = sBuilder.length();
    sBuilder.delete(length - 3, length);

    return sBuilder.toString();
  }

  public static String dump(List array) {
    StringBuilder sBuilder = new StringBuilder();

    if (null == array) {
      return sBuilder.toString();
    }

    for (Object o : array) {
      sBuilder.append(o.toString()).append("\n");
    }

    return sBuilder.toString();
  }

  public static String dump(Object[] array) {
    StringBuilder sBuilder = new StringBuilder();

    if (null == array || 0 == array.length) {
      return sBuilder.toString();
    }

    int size = array.length;
    for (int i = 0; i < size; ++i) {
      sBuilder.append(array[i]).append(", ");
    }

    int length = sBuilder.length();
    sBuilder.delete(length - 2, length);

    return sBuilder.toString();
  }

  public static String ArrayToString(String[] array) {
    StringBuilder sBuilder = new StringBuilder();

    if (null == array || 0 == array.length) {
      return sBuilder.toString();
    }

    int size = array.length;
    for (int i = 0; i < size; ++i) {
      sBuilder.append(array[i]);
    }
    return sBuilder.toString();
  }

  public static String genInClause(String json) {
    String result = null;

    if (StrKit.isBlank(json)) {
      return result;
    }

    JSONArray array = toJSONArray(json);

    if (null == array) {
      try {
        Integer.parseInt(json);
        result = "(" + json + ")";
      } catch (Exception e) {
      }
    } else {
      result = genInClause(array);
    }

    return result;
  }

  public static String genInClause(JSONArray array) {
    String result = null;

    if (null != array && array.size() > 0) {
      result = array.toJSONString().replace("[", "(").replace("]", ")");
    }

    return result;
  }

  public static String genInClause(int[] array) {
    JSONObject json = new JSONObject();
    json.put("array", array);
    return genInClause(json.getJSONArray("array"));
  }

  public static String genInClause(Object[] array) {
    String result = null;

    if (null != array && array.length > 0 && array[0] instanceof Integer) {
      JSONObject json = new JSONObject();
      json.put("array", array);
      result = genInClause(json.getJSONArray("array"));
    }

    return result;
  }

  public static JSONObject toJSONObject(Controller controller) {
    JSONObject json;
    String payload = HttpKit.readData(controller.getRequest());

    if (StrKit.notBlank(payload)) {
      json = JSONObject.parseObject(payload);
    } else {
      json = toJSONObject(controller.getParaMap());
    }
    return json;
  }

  /**
   * 将请求的所有参数转成 JSON
   */
  public static JSONObject toJSONObject(Map<String, String[]> map) {
    Map<String, String[]> sorted = new TreeMap<>(new KeyComparator());
    sorted.putAll(map);

    JSONObject result = new JSONObject();

    for (String key : sorted.keySet()) {
      String[] value = sorted.get(key);
      boolean isArray = key.endsWith("[]");

      String[] keys = key.split("[\\[\\]]+");
      int length = keys.length;
      JSONObject mid = result;
      for (int i = 0; i < length; ++i) {
        String k = keys[i];
        JSONObject json;

        if (1 == length) {
          result.put(k, isArray ? str2intArray(value) : str2int(value[0]));
          continue;
        }

        if (!mid.containsKey(k)) {
          if (i + 1 < length) {
            json = new JSONObject();
            mid.put(k, json);
          } else {
            json = mid;
          }
        } else {
          json = (JSONObject) mid.get(k);
        }

        if (i + 1 == length) {
          json.put(k, isArray ? str2intArray(value) : str2int(value[0]));
        } else {
          mid = json;
        }
      }
    }

    return mergeJSONArray(result);
  }

  private static JSONObject mergeJSONArray(JSONObject json) {
    for (String key : json.keySet()) {
      Object obj = json.get(key);
      if (obj instanceof JSONObject) {
        JSONObject o = json.getJSONObject(key);

        if (o.containsKey("0")) {
          JSONArray array = new JSONArray();
          for (String k : o.keySet()) {
            array.add(mergeJSONArray(o.getJSONObject(k)));
          }
          json.put(key, array);
        } else {
          mergeJSONArray(o);
        }
      }
    }

    return json;
  }

  /**
   * 字符串转 JSON 数组
   */
  public static JSONArray toJSONArray(String str) {
    JSONArray result = null;

    try {
      result = JSONArray.parseArray(str);
    } catch (Exception e) {
      // [Neo] Empty
    }

    return result;
  }

  /**
   * 字符串转 JSON
   */
  public static JSONObject toJSONObject(String str) {
    JSONObject result = null;

    try {
      result = JSONObject.parseObject(str);
    } catch (Exception e) {
      // [Neo] Empty
//      e.printStackTrace();
    }

    return result;
  }

  public static boolean toJSONObject(Record record, String key) {
    boolean result = false;

    if (null != record && StrKit.notBlank(key)) {
      String value = record.getStr(key);
      JSONObject json = toJSONObject(value);

      if (null != json) {
        record.set(key, json);
        result = true;
      }
    }

    return result;
  }

  public static boolean toJSONArray(Record record, String key) {
    boolean result = false;

    if (null != record && StrKit.notBlank(key)) {
      String value = record.getStr(key);
      JSONArray json = toJSONArray(value);

      if (null != json) {
        record.set(key, json);
        result = true;
      }
    }

    return result;
  }

  public static String toStringWithNull(JSON json) {
    String result = null;

    if (null != json) {
      result = JSON.toJSONString(json, SerializerFeature.WriteMapNullValue);
    }

    return result;
  }

  public static JSONArray mergeArray(JSONArray proto, JSONArray select,
      String k, JSONArray v) {
    JSONArray result = null;
    JSONArray shadow = null;

    if (null != proto) {
      result = (JSONArray) proto.clone();

      if (null != select) {
        shadow = (JSONArray) select.clone();
      }

      int size = result.size();
      for (int i = 0; i < size; ++i) {
        JSONObject first = result.getJSONObject(i);

        if (!first.containsKey("id")) {
          JSONArray dv = JSONArray.parseArray(v.toJSONString());
          first.put(k, dv);
          continue;
        }

        int id = first.getIntValue("id");

        if (null != shadow) {
          int ssize = shadow.size();
          boolean findInShadow = false;

          for (int ii = 0; ii < ssize; ++ii) {
            JSONObject sfirst = shadow.getJSONObject(ii);
            int sid = sfirst.getIntValue("id");

            if (sid == id) {
              String subArrayKey = "";
              boolean nested = false;

              for (String key : first.keySet()) {
                if (first.get(key) instanceof JSONArray) {
                  subArrayKey = key;

                  if (first.getJSONArray(key).getJSONObject(0)
                      .containsKey("id")) {
                    nested = true;
                    break;
                  }
                }
              }

              if (nested) {
                JSONArray merged = mergeArray(first.getJSONArray(subArrayKey),
                    sfirst.getJSONArray(subArrayKey), k, v);
                first.put(subArrayKey, merged);
              } else {
                first.put(k, sfirst.getJSONArray(k));
              }

              findInShadow = true;
              break;
            }
          }

          // [Neo] .TODO
          if (!findInShadow) {
            for (String key : first.keySet()) {
              if (first.get(key) instanceof JSONArray) {
                JSONArray arr = first.getJSONArray(key);
                if (arr.get(0) instanceof JSONObject &&
                    arr.getJSONObject(0).containsKey("id")) {
                  JSONArray merged = mergeArray(arr, null, k, v);
                  first.put(key, merged);
                  break;
                }
              }
            }
          }

        } else {
          boolean nested = false;

          for (String key : first.keySet()) {
            if (first.get(key) instanceof JSONArray) {
              JSONArray arr = first.getJSONArray(key);
              if (arr.get(0) instanceof JSONObject &&
                  arr.getJSONObject(0).containsKey("id")) {
                nested = true;
                JSONArray merged = mergeArray(arr, null, k, v);
                first.put(key, merged);
                break;
              }
            }
          }

          if (!nested) {
            JSONArray dv = JSONArray.parseArray(v.toJSONString());
            first.put(k, dv);
          }
        }
      }
    }

    return result;
  }

  public static String formatJsonDate(JSON json) {
    String result = null;

    if (null != json) {
      result = JSON.toJSONStringWithDateFormat(json, Consts.PATTERN_DATE,
          SerializerFeature.WriteMapNullValue
      );
    }

    return result;
  }

  public static String formatJsonDateTime(JSON json) {
    String result = null;

    if (null != json) {
      result = JSON.toJSONStringWithDateFormat(json, Consts.PATTERN_DATETIME,
          SerializerFeature.WriteMapNullValue);
    }
    Log.d(Strings.formatJsonDate(json));
    return result;
  }

  public static JSONObject formatPage(JSONObject json) {
    JSONObject result = null;

    if (null != json) {
      int size = json.getInteger("size");
      int page = json.getInteger("page");
      JSONArray array = json.getJSONArray("data");
      if (null != array && array.size() > 0) {
        if (page <= 1 && array.size() < size) {
          json.put("rows", array.size());
          int i = (array.size() - 1) / array.size() + 1;
          json.put("total", i <= 0 ? 0 : i);
        }
      } else {
        json.put("data", new JSONArray());
      }
      result = json;
    }

    return result;
  }

  /**
   * 获取 JSON 数组对象中特定的键值对
   *
   * @param array 数组对象，元素都是 JSON 对象
   * @param key 待提取的键
   */
  public static ArrayList<String> valuesOfJsonKey(JSONArray array, String
      key) {
    ArrayList<String> results = new ArrayList<>();

    if (null != array && array.size() > 0 && StrKit.notBlank(key)) {
      int size = array.size();
      for (int i = 0; i < size; ++i) {
        JSONObject object = array.getJSONObject(i);
        if (object.containsKey(key)) {
          results.add(object.get(key).toString());
        }
      }
    }

    return results;
  }

  /**
   * 将整数数组组合成字符串
   *
   * @param ids 数组
   * @param separator 分割符
   */
  public static String join(Integer[] ids, String separator) {
    StringBuilder sBuilder = new StringBuilder();

    for (Integer id : ids) {
      sBuilder.append(id).append(separator);
    }

    final int length = sBuilder.length();
    if (length > 0) {
      sBuilder.delete(length - 1, length);
    }

    return sBuilder.toString();
  }

  /**
   * 为手动添加的 Record 记录重新排序
   */
  @SuppressWarnings("unchecked")
  public static <T> T[] sortRecordColumns(T[] columns) {
    if (null == columns) {
      return null;
    }

    int length = columns.length;
    // [Neo] nothing I can do, but to suppress warnings
    T[] sorted = (T[]) new Object[length];

    int index = 0;
    for (int i = length - 2; i >= -1; i -= 2) {
      if (i >= 0) {
        sorted[index++] = columns[i];
      }

      sorted[index++] = columns[i + 1];
    }

    return sorted;
  }

  /**
   * 验证json
   **/
  public static boolean checkJsonArray(String str) {
    boolean result = false;

    if (!StrKit.isBlank(str)) {
      result = true;
      try {
        JSONArray.parseArray(str);
      } catch (Exception e) {
        // [Neo] .Empty
        result = false;
      }
    }
    return result;
  }

  /**
   * 验证json对象
   ***/
  public static boolean checkJson(String string) {
    boolean result = false;

    if (!StrKit.isBlank(string)) {
      result = true;
      try {
        JSONObject.parseObject(string);
      } catch (Exception e) {
        // [Neo] .Empty
        result = false;
      }
    }
    return result;
  }

  private static Object[] str2intArray(String[] str) {
    int length = str.length;
    boolean failed = false;
    Integer[] result = new Integer[length];

    for (int i = 0; i < length; ++i) {
      try {
        result[i] = Integer.parseInt(str[i]);
      } catch (Exception e) {
        if (StrKit.isBlank(str[i])) {
          result[i] = null;
        } else {
          failed = true;
          break;
        }
      }
    }

    return failed ? str : result;
  }

  private static Object str2int(String str) {
    boolean failed = false;
    Integer result = null;

    if (StrKit.isBlank(str)) {
      return null;
    }

    try {
      result = Integer.parseInt(str);
    } catch (Exception e) {
      failed = true;
    }

    return failed ? str : result;
  }

  public static int getInt(JSONObject req, String key, int defaultint) {
    int num = defaultint;
    if (null != req) {
      try {
        if (req.containsKey(key) && null != req.get(key) && StrKit
            .notBlank(req.get(key).toString())) {
          num = Integer.parseInt(req.get(key).toString());
        }
      } catch (Exception e) {

        e.printStackTrace();
      }
    }
    return num;
  }

  public static JSONObject getJSONObject(JSONObject req, String key,
      JSONObject defaultJson) {
    JSONObject json = defaultJson;
    if (null != req) {
      try {
        if (req.containsKey(key) && null != req.get(key)) {
          if (req.get(key) instanceof JSONObject) {
            json = req.getJSONObject(key);
          }
        }
      } catch (Exception e) {

        e.printStackTrace();
      }
    }
    return json;
  }

  public static JSONArray getJSONArray(JSONObject req, String key,
      JSONArray defaultJson) {
    JSONArray json = defaultJson;
    if (null != req) {
      try {
        if (req.containsKey(key) && null != req.get(key)) {
          if (req.get(key) instanceof JSONArray) {
            json = req.getJSONArray(key);
          }
        }
      } catch (Exception e) {

        e.printStackTrace();
      }
    }
    return json;
  }

  public static String getString(JSONObject req, String key,
      String defaultstring) {
    String str = defaultstring;
    if (null != req) {
      try {
        if (req.containsKey(key) && null != req.get(key)) {
          if (req.get(key) instanceof String) {
            str = req.getString(key).replace("'", "");
          }
        }
      } catch (Exception e) {

        e.printStackTrace();
      }
    }
    return str;
  }

  public static double getdouble(JSONObject req, String key,
      double defaultdouble) {
    Double result = defaultdouble;

    if (null != req) {
      try {
        if (req.containsKey(key) && null != req.get(key)) {
          if (req.get(key) instanceof Double) {
            result = req.getDouble(key);
          }
        }
      } catch (Exception e) {

        e.printStackTrace();
      }
    }

    return result;
  }

  public static Object getObject(JSONObject req, String key,
      Object def) {
    Object result = def;

    if (null != req) {
      try {
        if (req.containsKey(key) && null != req.get(key)) {
          result = req.get(key);
        }
      } catch (Exception e) {

        e.printStackTrace();
      }
    }

    return result;
  }

  public static float getfloat(JSONObject req, String key,
      float defaultfloat) {
    float result = defaultfloat;

    if (null != req) {
      try {
        if (req.containsKey(key) && null != req.get(key)) {
          if (req.get(key) instanceof Float) {
            result = req.getFloat(key);
          }
        }
      } catch (Exception e) {

        e.printStackTrace();
      }
    }

    return result;
  }

  public static Date getdata(JSONObject req, String key,
      Date defaultdata) {

    Date data = defaultdata;
    if (null != req) {
      try {
        if (req.containsKey(key) && null != req.get(key)) {
          if (req.get(key) instanceof Date) {
            data = req.getDate(key);
          }
        }
      } catch (Exception e) {

        e.printStackTrace();
      }
    }
    return data;
  }

  public static boolean getboolean(JSONObject req, String key,
      boolean defaultboolean) {
    boolean result = defaultboolean;
    if (null != req) {
      try {
        if (req.containsKey(key) && null != req.get(key)) {
          if (req.get(key) instanceof Boolean) {
            result = req.getBoolean(key);
          }
        }
      } catch (Exception e) {

        e.printStackTrace();
      }
    }
    return result;
  }

  public static String toScale(long number, int N, char[] NSample) {
    Long rest = number;
    Stack<Character> stack = new Stack<>();
    StringBuilder result = new StringBuilder();

    while (rest != 0) {
      stack.add(NSample[new Long(rest % N).intValue()]);
      rest = rest / N;
    }

    while (!stack.isEmpty()) {
      result.append(stack.pop());
    }

    return result.length() == 0
           ? String.valueOf(NSample[0])
           : result.toString();
  }

  public static String SHA1(String str) {
    if (str == null || str.length() == 0) {
      return null;
    }

    try {
      MessageDigest digest = MessageDigest.getInstance("SHA1");
      digest.update(str.getBytes(Consts.ENCODE));

      byte[] data = digest.digest();
      int length = data.length;

      int k = 0;
      char buf[] = new char[length * 2];

      for (int i = 0; i < length; i++) {
        byte byte0 = data[i];
        buf[k++] = HEX[byte0 >>> 4 & 0xf];
        buf[k++] = HEX[byte0 & 0xf];
      }

      return new String(buf);
    } catch (Exception e) {
      return null;
    }
  }


  public static JSONObject parseIdcard(String idcard) {
    JSONObject result = new JSONObject();

    if (StrKit.isBlank(idcard) ||
        (idcard.length() != 15 && idcard.length() != 18)) {
      result.put(Consts.JSON_RES_RESULT, Result.kBadLength);
      return result;
    }

    String tmp = "";
    if (idcard.length() == 18) {
      tmp = idcard.substring(0, 17);
    } else if (idcard.length() == 15) {
      tmp = idcard.substring(0, 6) + "19" + idcard.substring(6, 15);
    }

    Pattern onlyNumeric = Pattern.compile("[0-9]*");
    if (!onlyNumeric.matcher(tmp).matches()) {
      result.put(Consts.JSON_RES_RESULT, Result.kBadType);
      return result;
    }

    if (!LOCAL_CODE.containsKey(tmp.substring(0, 2))) {
      result.put(Consts.JSON_RES_RESULT, Result.kBadLocalCode);
      return result;
    }

    String strYear = tmp.substring(6, 10);
    String strMonth = tmp.substring(10, 12);
    String strDay = tmp.substring(12, 14);

    String birthday = strYear + "-" + strMonth + "-" + strDay;
    Date birthdayDate = null;

    try {
      birthdayDate = Dates.DATE_FORMATTER.parse(birthday);
    } catch (ParseException e) {
      result.put(Consts.JSON_RES_RESULT, Result.kBadBirthday);
      return result;
    }

    GregorianCalendar gc = new GregorianCalendar();
    int age = gc.get(Calendar.YEAR) - Integer.parseInt(strYear);

    if (gc.getTime().getTime() - birthdayDate.getTime() < 0 || age > 150) {
      result.put(Consts.JSON_RES_RESULT, Result.kBadYear);
      return result;
    }

    if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {
      result.put(Consts.JSON_RES_RESULT, Result.kBadMonth);
      return result;
    }

    if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
      result.put(Consts.JSON_RES_RESULT, Result.kBadDay);
      return result;
    }

    int check = 0;
    for (int i = 0; i < 17; i++) {
      check =
          check + Integer.parseInt(String.valueOf(tmp.charAt(i))) * Integer
              .parseInt(ID_WI[i]);
    }

    check = check % 11;
    String strVerifyCode = ID_SUFFIX[check];
    tmp = tmp + strVerifyCode;

    if (idcard.length() == 18 && tmp.equals(idcard)) {
      result = new JSONObject();
      result.put("idcard", tmp);
      result.put("birthday", birthdayDate);
      result.put("age", age);
      result.put(Consts.JSON_RES_RESULT, Result.kSuccess);
    } else {
      result.put(Consts.JSON_RES_RESULT, Result.kBadCheck);
    }

    return result;
  }

  private static class KeyComparator implements Comparator<String> {

    @Override
    public int compare(String o1, String o2) {
      return o1.compareTo(o2);
    }
  }

  /**
   * 去重
   *
   * @author lc
   */
  public static List<Record> removeDuplicateOrder(List<Record> orderList,
      String order) {
    Set<Record> set = new TreeSet<>(new Comparator<Record>() {
      @Override
      public int compare(Record a, Record b) {
        // 字符串则按照asicc码升序排列
        return a.getStr(order).compareTo(b.getStr(order));
      }
    });

    set.addAll(orderList);
    return new ArrayList<>(set);
  }

  public static List<Model> search(String name, List<Model> list) {
    Pattern pattern = Pattern.compile(name);
    for (int i = 0; i < list.size(); i++) {
      Matcher matcher = pattern.matcher(list.get(i).toString());
      if (matcher.find()) {
        list.remove(list.get(i));
      }
    }
    return list;
  }

  //对象去重
  public static JSONArray removeStringListDupli(JSONArray stringList) {
    if (null != stringList && stringList.size() > 0) {
      Set set = new LinkedHashSet<>();
      set.addAll(stringList);
      stringList.clear();
      stringList.addAll(set);
    }
    return stringList;
  }

  /**
   * 获取属性值
   *
   * @param array filter  or  search
   * @param o key值
   * @param is_object true：返回该key值对应对象；false:返回该key值对应对象的value
   * @author lc
   */
  public static Object get(JSONArray array, Object o, boolean is_object) {
    Object object = null;
    if (null != array && array.size() > 0) {
      for (int i = 0; i < array.size(); i++) {
        if (array.getJSONObject(i).containsKey(o)) {
          if (is_object) {
            object = array.getJSONObject(i);
          } else {
            object = array.getJSONObject(i).get(o);
          }
        }
      }
    }
    return object;
  }


  //新版本排序
  public static String sort(String sql, JSONArray sort,
      String def) {
    String key = null;
    String order = null;
    if (null != sort && sort.size() > 0) {
      for (int i = 0; i < sort.size(); i++) {
        JSONObject object = sort.getJSONObject(i);
        Set keys = object.keySet();
        key = keys.iterator().next().toString();
        order = object.getString(key);
        if (StrKit.notBlank(key) && i == 0) {
          if (key.contains("CONVERT")) {
            sql = sql + " ORDER BY " + key + " ";
          } else {
            sql = sql + " ORDER BY `" + key + "` ";
          }
          if (StrKit.notBlank(order)) {
            sql = sql + order;
          }
        }
        if (StrKit.notBlank(key) && i > 0) {
          if (key.contains("CONVERT")) {
            sql = sql + "," + key + " ";
          } else {
            sql = sql + ",`" + key + "` ";
          }
          if (StrKit.notBlank(order)) {
            sql = sql + order;
          }
        }
      }
    } else if (StrKit.notBlank(def)) {
      sql = sql + " ORDER BY " + def;
    }
    return sql;
  }

  public static boolean is_mobile(String mobile) {
    boolean r = false;
    if (StrKit.notBlank(mobile)) {
      if (mobile.length() == 11) {
        Pattern p = Pattern.compile(REGEX_MOBILE);
        Matcher m = p.matcher(mobile);
        r = m.matches();
      }
    }
    return r;
  }
}